﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using XKPlatform.Common;
using XKPlatform.Common.Enums;
using XKPlatform.DataModels;
using XKPlatform.DataModels.Dao.BaseEntity;
using XKPlatform.DataModels.ReturnModel;
using XKPlatform.IService;

namespace XKPlatform.Controllers.SysController
{
    [Route("[controller]/[action]")]
    public class SysUserController : BaseController
    {
        private readonly ISysUserService _iservice;
        public SysUserController(ISysUserService iservice, IHttpContextAccessor httpContext) : base(httpContext)
        {
            _iservice = iservice;
        }
        /// <summary>
        /// 查询获取数据
        /// </summary>
        /// <param name="searchModel">查询参数</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetList([FromBody] SysUserSearchParams search)
        {
            PageInfo pageinfo = new PageInfo();
            pageinfo.PageIndex = search.Page;
            pageinfo.PageSize = search.Limit;
            pageinfo.IsPaging = search.IsPage == null ? true : Convert.ToBoolean(search.IsPage);
            long count = 0;

            List<SortInfo<SysUser, object>> sorLst = new List<SortInfo<SysUser, object>>();
            SortInfo<SysUser, object> sorItem = new SortInfo<SysUser, object>();
            sorItem.SortMethods = SortEnum.Desc;
            //#注：默认按创建时间倒叙，如果有自定义排序规则修改此处
            sorItem.Orderby = o => o.CreatedOn;
            sorLst.Add(sorItem);
            //过滤超级管理员
            Expression<Func<SysUser, bool>> where = o => o.RecordStatus == false && o.UserID.ToString() != "BB8A9356-E812-46A8-ABFA-8D3956F7ACF3";
            //组装查询条件

            if (!string.IsNullOrWhiteSpace(search.DepartmentID))
            {
                where = where.And(o => o.DepartmentID.ToString() == search.DepartmentID);
            }

            if (!string.IsNullOrWhiteSpace(search.UserName))
            {
                where = where.And(o => o.UserName.Contains(search.UserName));
            }

            if (!string.IsNullOrWhiteSpace(search.Email))
            {
                where = where.And(o => o.Email.Contains(search.Email));
            }

            if (!string.IsNullOrWhiteSpace(search.Mobile))
            {
                where = where.And(o => o.Mobile.Contains(search.Mobile));
            }

            if (!string.IsNullOrWhiteSpace(search.DefaultRoleIDs))
            {
                where = where.And(o => o.DefaultRoleID.ToString() == search.DefaultRoleIDs);
            }



            var ret = _iservice.GetList(where, sorLst, pageinfo);
            count = ret.count;
            var list = ret.list;

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success), data = list, count = Convert.ToInt32(count) });

        }
        /// <summary>
        /// 新增或修改
        /// </summary>
        /// <param name="save"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveOrEdit([FromBody] SysUser save)
        {
            //只有develop用户才能创建develop用户
            if (save.DefaultRoleID?.ToString().ToUpper() == HttpContextCore.developID && userInfo.DefaultRoleID.ToString() != HttpContextCore.developID)
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.NoPermission, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.NoPermission) });
            }

            //判断用户是否重复 
            var lst = _iservice.GetList(o => o.UserID != save.UserID && o.UserNo == save.UserNo).list;
            if (lst != null && lst.Count > 0)
            {
                //存在用户名
                return Json(new BasePageModel { code = (int)MsgCodeEnum.UserNoIsExist, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.UserNoIsExist) });

            }
            //判断邮箱是否存在
            if (!string.IsNullOrEmpty(save.Email))
            {
                var emlst = _iservice.GetList(o => o.Email == save.Email && o.UserID != save.UserID && o.RecordStatus == false).list;
                if (emlst != null && emlst.Count > 0)
                {
                    //邮箱存在
                    return Json(new BasePageModel { code = (int)MsgCodeEnum.EmailIsExist, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.EmailIsExist) });
                }
            }
            //判断主键为空 则是新增
            if (!save.UserID.HasValue)
            { 
                //#补充主键 创建信息 
                save.UserID = Guid.NewGuid();
                save.CreatedBy = userInfo.UserNo;
                save.CreatedOn = DateTime.Now;//.ToString("yyyy-MM-dd:HH:mm:ss");
                save.RecordStatus = false;
                // 默认初始密码 
                string password = "railway@321";// GetrandomPassWord();
                save.Password= EncryptHelper.MD5(password);
                _iservice.AddModel(save);

            }
            else
            { 
                var model = _iservice.GetModel(o => o.UserID == save.UserID);
                model.UserName = save.UserName;
                model.Email = save.Email;
                model.Mobile = save.Mobile;
                model.DefaultRoleID = save.DefaultRoleID;

                _iservice.UpdateModel(model, o => o.UserID == save.UserID);

            }

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });

        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelAll([FromBody] List<string> ids)
        {
            var isDelete = false;
            //TODO 判断如果是develop 不能删除
            isDelete = _iservice.Delete(o => ids.Contains(o.UserID.ToString()));

            if (isDelete)
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });
            }
            else
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.Failed, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Failed) });

            }
        }
    }
}
